import tkinter as tk
import uuid
from tkinter import messagebox

from until.auth.sqllite_util import SQLiteUtil


class CustomPasswordDialog:
    def __init__(self, master=None, title="软件授权", prompt="请输入密码："):
        node_id = self.get_node_id()
        tk.Tk().withdraw()
        self.master = master
        self.title = title
        self.prompt = f'您的设备码：{node_id}\n请输入激活码：'
        self.password = None

    def get_node_id(self):
        uid = uuid.getnode()
        return uid

    def run(self):
        # 创建一个顶层窗口作为对话框
        self.top = tk.Toplevel(self.master)
        self.top.title(self.title)
        self.top.geometry("300x140")

        # 创建一个标签显示提示信息
        tk.Label(self.top, text=self.prompt, justify='left').pack(side="top", fill="x", padx=5, pady=5)

        # 创建一个密码输入框
        self.entry = tk.Entry(self.top, show='*')
        self.entry.pack(side="top", fill="x", padx=5, pady=5)

        # 创建一个确认按钮
        confirm_button = tk.Button(self.top, text="确认密码", command=self.get_password)
        confirm_button.pack(side="bottom", fill="x", padx=5, pady=5)

        # 等待用户输入并点击确认按钮
        self.top.transient(self.master)
        self.top.grab_set()
        self.top.wait_window(self.top)

        # 返回输入的密码
        return self.password

    def get_password(self):
        # 获取输入的密码
        self.password = self.entry.get()
        # 销毁顶层窗口
        self.top.destroy()


# 使用自定义密码对话框
def authenticate_user():
    uid = uuid.getnode()
    correct_password = str(hex(int(uid) * 32089 - 1024 * 1024)).replace('0x', '')

    password_dialog = CustomPasswordDialog()
    entered_password = password_dialog.run()
    if entered_password == correct_password:
        sqlite = SQLiteUtil()
        sqlite.insert_activation_code((uid, correct_password))
        messagebox.showinfo("认证", "激活码正确，软件激活成功！")
        return True
    else:
        messagebox.showerror("认证", "激活码错误，软件激活失败！")
        return False


def auth_software():
    uid = uuid.getnode()

    sqlite = SQLiteUtil()
    code = sqlite.query_activation_code()
    if code:
        print('软件激活成功')
        correct_password = str(hex(uid * 32089 - 1024 * 1024)).replace('0x', '')
        if code == correct_password:
            return True
        else:
            return False
    else:
        return authenticate_user()


# 测试认证函数
if __name__ == "__main__":
    authenticate_user()
